﻿using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.IO;
using System.Linq;
using System.Text;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.ComponentModel.Composition.Hosting;
using BusinessInterfaces;
using Microsoft.WindowsAzure;
using Microsoft.WindowsAzure.ServiceRuntime;
using Microsoft.WindowsAzure.StorageClient;

namespace WebRole1
{
    public partial class _Default : System.Web.UI.Page
    {


        protected void Page_Load(object sender, EventArgs e)
        {
            UpdateUI();
        }

        #region Update Methods
        private void UpdateUI()
        {
            StringBuilder result = new StringBuilder();

            // TODO: need a better way to dynamically read contents of the catalog?
            try
            {
                IDiagnostics diagnostics = default(IDiagnostics);

                diagnostics = MEFContext.MEFContainer.GetExportedValue<IDiagnostics>();
                diagnostics.Log("Successfully loaded: IDiagnostics");

                // we have diagnostics, now try to read additional types
                try
                {
                    foreach(IBusinessRule<ICustomer> businessRule in  MEFContext.MEFContainer.GetExportedValues<IBusinessRule<ICustomer>>())
                    {
                        diagnostics.Log(string.Format("Successfully loaded: rule type {0}",
                                        businessRule.GetType().FullName));
                    }

                }
                catch (Exception ex)
                {
                    // ICustomer failed, likely because the container is not aware of it yet
                    diagnostics.LogException(ex);
                }

                // build the output for the UI
                foreach (string s in diagnostics.LogMessages)
                {
                    result.Append(s + "\r\n");
                }
            }
            catch (Exception ex)
            {
                result.Append("Failed to load: IDiagnostics (Missing from Catalog?)");
                result.Append(ex.Message);
            }

            ResourceTextBox.Text = result.ToString();
        }



        #endregion

        #region Event Handlers
        protected void UpdateCatalogButton_Click(object sender, EventArgs e)
        {
            MEFContext.UpdateCatalog();
            this.UpdateUI();
        }
        #endregion
    }
}
